package org.kingdom.utils.qrcode;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信小程序二维码生成
 */
@RequestMapping(value = "qrcode")
public class WxQrCode{
	 /**
     * 获取小程序的access_token码
     *
     * @return
     */
    @GetMapping(value = "/getAccessToken")
    public Object getAccessToken() {
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/cgi-bin/tokenObject");
        //固定参数
        url.append("grant_type=").append("client_credential");
        //微信小程序的appId和secret
        url.append("&appid=").append("appId");
        url.append("&secret=").append("appSecret");

        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity he = response.getEntity();//拿到返回的HttpResponse的"实体"

            String content = EntityUtils.toString(he);
            cn.hutool.json.JSONObject obj = JSONUtil.parseObj(content);

            String access_token = obj.getStr("access_token");
            qrCode(access_token);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return "操作失败";
        }

    }

    public void qrCode(String accessToken) {
        Map<String, Object> params = new HashMap<>();
        //参数,一个可以直接放入参数例如:1 多个例如：id=1&name=2&...
        params.put("scene", "需要的参数");
        params.put("path", "pages/index/index"); //扫码后进入小程序的页面位置
        params.put("width", 430);//不是必须，需要的宽度，默认430x430，最小280最大1280
        params.put("is_hyaline", true);//是否透明底色
        params.put("auto_color", false);//是否线条变色
        //auto_color=false 生效
        params.put("line_color", JSONUtil.toBean("{'r':255,'g':0,'b':0}", Object.class));

        try {
            //构建一个Client
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost =
                    new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimitObjectaccess_token=" + accessToken);
            //添加请求头
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

            //将map集合转换成字符串
            String body = JSON.toJSONString(params);
            StringEntity entity = new StringEntity(body);
            //设置图片类型
            entity.setContentType("image/jpg");
            httpPost.setEntity(entity);
            //执行请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            //获取图片
            InputStream inputStream = httpResponse.getEntity().getContent();
            //文件名加后缀，文件后缀要一致
            String name = "xiaochengxu.jpg";

            //图片保存路径
            String path = "D:\\";
            //保存图片
            saveToImgByInputStream(inputStream, path, name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将二进制转换成文件保存
     *
     * @param instreams 二进制流
     * @param imgPath   图片的保存路径
     * @param imgName   图片的名称
     */
    public void saveToImgByInputStream(InputStream instreams, String imgPath, String imgName) throws Exception {
        if (instreams != null) {
            File file = new File(imgPath, imgName);//可以是任何图片格式.jpg,.png等
            File filePath = new File(imgPath);
            if (!filePath.exists()) {
                filePath.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int nRead = 0;
            while ((nRead = instreams.read(b)) != -1) {
                fos.write(b, 0, nRead);
            }
            fos.flush();
            fos.close();
        }
    }

    /*
    <dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-all</artifactId>
			<version>5.4.1</version>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.73</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.12</version>
		</dependency>
    */

}
